package com.sunsharing.party.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.util.UrlPathHelper;

import com.sunsharing.party.ConfigParam;



/**
 * HttpServletRequest帮助类
 */
public class RequestUtils {
	private static final Logger log = Logger.getLogger(RequestUtils.class);

	private static final String POST = "POST";
	private static final String UTF8 = "UTF-8";
	
	
	public static class RequestURL{
        String webPath; //到上下文根
        String fullURL; //当前全路径，包含queryString

        public RequestURL(String webPath, String fullURL) {
            this.webPath = webPath;
            this.fullURL = fullURL;
        }

        public String getWebPath() {
            return webPath;
        }

        public void setWebPath(String webPath) {
            this.webPath = webPath;
        }

        public String getFullURL() {
            return fullURL;
        }

        public void setFullURL(String fullURL) {
            this.fullURL = fullURL;
        }
    }
	/**
	 * 获取QueryString的参数，并使用URLDecoder以UTF-8格式转码。如果请求是以post方法提交的，
	 * 那么将通过HttpServletRequest#getParameter获取。
	 * 
	 * @param request
	 *            web请求
	 * @param name
	 *            参数名称
	 * @return
	 */
	public static String getQueryParam(HttpServletRequest request, String name) {
		if (StringUtils.isBlank(name)) {
			return null;
		}
		if (request.getMethod().equalsIgnoreCase("POST")) {
			return request.getParameter(name);
		}
		String s = request.getQueryString();
		if (StringUtils.isBlank(s)) {
			return null;
		}
		try {
			s = URLDecoder.decode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			log.error("encoding " + UTF8 + " not support?", e);
		}
		String[] values = parseQueryString(s).get(name);
		if (values != null && values.length > 0) {
			return values[values.length - 1];
		} else {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static Map<String, Object> getQueryParams(HttpServletRequest request) {
		Map<String, String[]> map;
		if (request.getMethod().equalsIgnoreCase(POST)) {
			map = request.getParameterMap();
		} else {
			String s = request.getQueryString();
			if (StringUtils.isBlank(s)) {
				return new HashMap<String, Object>();
			}
			try {
				s = URLDecoder.decode(s, UTF8);
			} catch (UnsupportedEncodingException e) {
				log.error("encoding " + UTF8 + " not support?", e);
			}
			map = parseQueryString(s);
		}

		Map<String, Object> params = new HashMap<String, Object>(map.size());
		int len;
		for (Map.Entry<String, String[]> entry : map.entrySet()) {
			len = entry.getValue().length;
			if (len == 1) {
				params.put(entry.getKey(), entry.getValue()[0]);
			} else if (len > 1) {
				params.put(entry.getKey(), entry.getValue());
			}
		}
		return params;
	}

	/**
	 * 
	 * Parses a query string passed from the client to the server and builds a
	 * <code>HashTable</code> object with key-value pairs. The query string
	 * should be in the form of a string packaged by the GET or POST method,
	 * that is, it should have key-value pairs in the form <i>key=value</i>,
	 * with each pair separated from the next by a &amp; character.
	 * 
	 * <p>
	 * A key can appear more than once in the query string with different
	 * values. However, the key appears only once in the hashtable, with its
	 * value being an array of strings containing the multiple values sent by
	 * the query string.
	 * 
	 * <p>
	 * The keys and values in the hashtable are stored in their decoded form, so
	 * any + characters are converted to spaces, and characters sent in
	 * hexadecimal notation (like <i>%xx</i>) are converted to ASCII characters.
	 * 
	 * @param s
	 *            a string containing the query to be parsed
	 * 
	 * @return a <code>HashTable</code> object built from the parsed key-value
	 *         pairs
	 * 
	 * @exception IllegalArgumentException
	 *                if the query string is invalid
	 * 
	 */
	public static Map<String, String[]> parseQueryString(String s) {
		String valArray[] = null;
		if (s == null) {
			throw new IllegalArgumentException();
		}
		Map<String, String[]> ht = new HashMap<String, String[]>();
		StringTokenizer st = new StringTokenizer(s, "&");
		while (st.hasMoreTokens()) {
			String pair = (String) st.nextToken();
			int pos = pair.indexOf('=');
			if (pos == -1) {
				continue;
			}
			String key = pair.substring(0, pos);
			String val = pair.substring(pos + 1, pair.length());
			if (ht.containsKey(key)) {
				String oldVals[] = (String[]) ht.get(key);
				valArray = new String[oldVals.length + 1];
				for (int i = 0; i < oldVals.length; i++) {
					valArray[i] = oldVals[i];
				}
				valArray[oldVals.length] = val;
			} else {
				valArray = new String[1];
				valArray[0] = val;
			}
			ht.put(key, valArray);
		}
		return ht;
	}

	public static Map<String, String> getRequestMap(HttpServletRequest request,
			String prefix) {
		return getRequestMap(request, prefix, false);
	}

	public static Map<String, String> getRequestMapWithPrefix(
			HttpServletRequest request, String prefix) {
		return getRequestMap(request, prefix, true);
	}

	@SuppressWarnings("unchecked")
	private static Map<String, String> getRequestMap(
			HttpServletRequest request, String prefix, boolean nameWithPrefix) {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration<String> names = request.getParameterNames();
		String name, key, value;
		while (names.hasMoreElements()) {
			name = names.nextElement();
			if (name.startsWith(prefix)) {
				key = nameWithPrefix ? name : name.substring(0,prefix.length());
				value = StringUtils.join(request.getParameterValues(name), ',');
				map.put(key, value);
			}
		}
		return map;
	}

	/**
	 * 获取访问者IP
	 * 
	 * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
	 * 
	 * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
	 * 如果还不存在则调用Request .getRemoteAddr()。
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}
	
	public static String cleanIpv6(String ipv6) {
		return ipv6.replace("：", ":");
	}
	public static String replaceStr(String str) {
		str = str.replace("＞", ">").replace("＼", "");
		String reg_img = "<[^>]*>";
		Pattern patter_img = Pattern.compile(reg_img);
		Matcher matcher_img = patter_img.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher_img.find()) {
			String imgAddress = matcher_img.group();
			imgAddress = imgAddress.replaceAll("：", ":");
			matcher_img.appendReplacement(sb, imgAddress);
		}
		matcher_img.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 获得当的访问路径
	 * 
	 * HttpServletRequest.getRequestURL+"?"+HttpServletRequest.getQueryString
	 * 
	 * @param request
	 * @return
	 */
	public static String getLocation(HttpServletRequest request) {
		UrlPathHelper helper = new UrlPathHelper();
		StringBuffer buff = request.getRequestURL();
		String uri = request.getRequestURI();
		String origUri = helper.getOriginatingRequestUri(request);
		buff.replace(buff.length() - uri.length(), buff.length(), origUri);
		String queryString = helper.getOriginatingQueryString(request);
		if (queryString != null) {
			buff.append("?").append(queryString);
		}
		return buff.toString();
	}

	public static void main(String[] args) {
		System.out.println(cleanIpv6("240e：9c：3085：9101：c5ce：43c3：2ecd：bdd9"));
	}
	/**
     * 微信 获取地址
     * @param weixinUrl
     * @param request
     * @return
     */
    public static RequestURL getFullRequestURL(String weixinUrl,HttpServletRequest request){
        String location  =   weixinUrl.substring(0, weixinUrl.length()-1);
        
        String reqUrl =  location + request.getServletPath();      //请求页面或其他地址
        if(request.getQueryString() != null){
            reqUrl = reqUrl + "?" + (request.getQueryString()); //参数
        }
        return new RequestURL(location,reqUrl);
    }
    public static String getProxyIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		System.out.println("ip1:" + ip + ":当前:" + request.getRemotePort()
				+ "/本机:" + request.getLocalPort() + "/服务:"
				+ request.getServerPort());
		System.out.println("ip2:" + request.getHeader("X-Real-IP"));
		System.out.println("ip3:" + request.getRemoteAddr());
//		System.out.println("ip4:"+getServerIp());
//		try {
////			printParameter();
//		} catch (SocketException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
		/*String ip5 = "";
		try {
			// System.out.println("ip4:"+InetAddress.getLocalHost().getHostAddress());
			// System.out.println("ip5:"+InetAddress.getAllByName(ConfigParam.normalNetUrl)[0].getHostAddress());
			ip5 = InetAddress.getByName(ConfigParam.normalNetUrl)
					.getHostAddress();
			System.out.println("ip5:" + ip5);
			System.out.println("ip6:"
					+ InetAddress.getByName(ConfigParam.normalInnerUrl)
							.getHostAddress());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			if (!StringUtils.isBlank(ip5)) {
				return returnIP(ip5);
			}
		}*/
		if (!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			// int index = ip.indexOf(",");
			// if(index != -1){
			for (String ip1 : ip.split(",")) {
				return returnIP(ip1);
			}
			// return ip.split(",")[ip.split(",").length-1].trim();
			// return ip.substring(0,index);
			// }
			// else{
			// return ip;
			// }
		}
		ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return returnIP(ip);
		}
		return returnIP(request.getRemoteAddr());
	}
    private static String returnIP(String ip) {
		if (ip.trim().startsWith(ConfigParam.normalNetUrl.split("\\.")[0])) {
			return ConfigParam.normalNetUrl;
		} else if (ip.trim().startsWith(ConfigParam.normalInnerUrl.split("\\.")[0])) {
			return ConfigParam.normalInnerUrl;
		}
		return ip;
	}
}
